
from freedel.contentstore.models import *
import models

def _encode_content(strx):
    """ Encode content to convert to ascii.

        Returns an ascii string.

    """
    
    assert(type(strx) == type(""))

    return strx.encode('uu')

def _decode_content(strx):
    """ Decode content to from ascii.

        Returns a string.

    """

    asssert(type(strx) == type(""))

    return strx.decode('uu')

def add_content(content, content_type = "default"):
    """ Add new content

        Returns corresponding ContentInfo object
        
    """

    # add/find content type

    ct, t = VersionedContentType.objects.get_or_create(name = content_type)
    
    # add content info

    ci = VersionedContentInfo.objects.create(content_type = ct)
    
    # add content
    cv = ci.current_version
    ec = _encode_content(content)
    vcs = VersionedContentStore.objects.create(content_info = ci,
                                               content = ec,
                                               content_version = cv)
                                               

    return ci

def update_content(content_info, content):
    """ Update existing content

        Returns None

    """

    # get next version

    nv = content_info.current_version + 1
    
    # update content

    content_info.current_version = nv
    content_info.save()
    
    vcs = VersionedContentStore.objects.create(content_info = content_info,
                                               content = content,
                                               content_version = nv)

def get_content(content_info, version):
    """ Return specific version of content.

        Returns the content as a string.

    """

    vcs = None

    vcs = VCStore.objects.get(content_info = content_info,
                                            content_version = version)

    return _decode_content(vcs.content)

